package com.tanhua.service;

import com.tanhua.Intercepter.UserHolder;
import com.tanhua.config.template.FaceTemeplate;
import com.tanhua.config.template.OssTemeplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.exception.BusinessExecption;
import com.tanhua.model.domain.ErrorResult;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @Autowired
    private OssTemeplate ossTemeplate;//阿里云文件存储服务

    @Autowired
    private FaceTemeplate faceTemeplate;//人脸识别
    @DubboReference
    private UserInfoApi userInfoApi;



    /**
     * 根据id查询用户信息
     *
     * @param id
     */
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /**
     * 添加用户信息
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }


    /**
     * 上传头像
     *
     * @param headphoto
     * @param id
     * @throws IOException
     */
    public void updateHead(MultipartFile headphoto, Long id) throws IOException {
        //1.使用阿里云文件存储服务将文件上传并返回文件地址
        String upload = ossTemeplate.upload(headphoto.getOriginalFilename(), headphoto.getInputStream());
        //2.百度人脸识别
        boolean flag = faceTemeplate.Face(upload);

        if (!flag) {
            //图像验证失败
            throw new BusinessExecption(ErrorResult.faceError());
        } else {
            //       调用接口更新
            UserInfo userInfo = new UserInfo();
            userInfo.setAvatar(upload);
            userInfo.setId(id);
            userInfoApi.update(userInfo);
        }
    }


    /**
     * 修改用户资料
     *
     * @param userInfo
     */
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
